package com.loklok.confuse.ui;

import cn.hutool.core.collection.CollectionUtil;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import com.loklok.confuse.extension.PathConfigSettingCache;
import com.loklok.confuse.model.CodePathConfig;
import com.loklok.confuse.model.ConfuseConfig;
import com.loklok.confuse.util.CommonUtil;
import com.loklok.confuse.util.LocalFileUtils;
import com.loklok.confuse.util.VelocityUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class GenerateFullCodeDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JTextField newPackageName;
    private JList choseCodeService;


    public GenerateFullCodeDialog(AnActionEvent anActionEvent) {
        setContentPane(contentPane);
        setTitle("codeConfuse");
        setSize(800, 500);
        setLocation(600, 200);
        setModal(true);
        setResizable(true);
        getRootPane().setDefaultButton(buttonOK);

        PathConfigSettingCache state = PathConfigSettingCache.getInstance(anActionEvent.getProject());
        Project project = anActionEvent.getProject();
        if (state == null || state.getConfig() == null || state.getConfig().requiredFieldsEmpty()) {
            CommonUtil.configureMessageReminders(project);
            return;

        }
        CodePathConfig config = state.getConfig();
        List<ConfuseConfig.LoadFullCodeConfig> loadFullCodeConfigs = config.loadFullCodeConfigObj();

        setJListData(loadFullCodeConfigs);

        // 监听事件
        buttonOK.addActionListener(e -> {

            buttonOK.setEnabled(false);
            String name = newPackageName.getText();
            List<String> checkServiceName = getSelectedServiceName();
            if (userOperateNoPass(name, checkServiceName)) {
                buttonOK.setEnabled(true);
                return;
            }


            try {

                List<ConfuseConfig.LoadCodeConfigItem> items = new ArrayList<>();
                loadFullCodeConfigs.stream().filter(it -> checkServiceName.contains(it.getServiceName())).forEach(item -> item.getItems().stream()
                        .forEach(configItem -> configItem.getClassNames().stream().forEach(classNameItem -> {
                            ConfuseConfig.LoadCodeConfigItem loadCodeConfigItem = new ConfuseConfig.LoadCodeConfigItem();
                            loadCodeConfigItem.setType(configItem.getType());
                            loadCodeConfigItem.setClassName(classNameItem);
                            loadCodeConfigItem.setLoadPath(configItem.getLoadPath());
                            loadCodeConfigItem.setMethods(configItem.getMethods());
                            items.add(loadCodeConfigItem);
                        })));


                LocalFileUtils.backgroundGenerateCode(anActionEvent, project, config, name, items);

            } catch (Exception ex) {
                ApplicationManager.getApplication().invokeLater(() -> Messages.showMessageDialog("An error occurred: " + ex.getMessage(), "Error", Messages.getErrorIcon()));
                return;
            }
            onOK();
        });
    }



    private List<String> getSelectedServiceName() {
        List selectedValuesList = this.choseCodeService.getSelectedValuesList();
        return selectedValuesList;
    }

    private void setJListData(List<ConfuseConfig.LoadFullCodeConfig> loadFullCodeConfigs) {
        List<String> serviceNames = loadFullCodeConfigs.stream().map(it -> it.getServiceName()).collect(Collectors.toList());
        this.choseCodeService.setListData(serviceNames.toArray());
    }

    private boolean userOperateNoPass(String name, List<String> checkServiceName) {
        if (StringUtils.isEmpty(name)) {
            Messages.showMessageDialog("请输入包名称！", "error massage:", Messages.getErrorIcon());
            return true;
        }

        if (CollectionUtil.isEmpty(checkServiceName)) {
            Messages.showMessageDialog("请正确需要生成那个接口", "error massage:", Messages.getErrorIcon());
            return true;
        }
        return false;
    }

    private void onOK() {
        // add your code here
        dispose();
    }

    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        contentPane = new JPanel();
        contentPane.setLayout(new GridLayoutManager(1, 1, new Insets(10, 10, 10, 10), -1, -1));
        final JPanel panel1 = new JPanel();
        panel1.setLayout(new GridLayoutManager(3, 1, new Insets(0, 0, 0, 0), -1, -1));
        contentPane.add(panel1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        final JPanel panel2 = new JPanel();
        panel2.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
        panel1.add(panel2, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        panel2.setBorder(BorderFactory.createTitledBorder(null, "选择生成的接口", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        final JScrollPane scrollPane1 = new JScrollPane();
        panel2.add(scrollPane1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
        choseCodeService = new JList();
        choseCodeService.setLayoutOrientation(0);
        scrollPane1.setViewportView(choseCodeService);
        final JPanel panel3 = new JPanel();
        panel3.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
        panel1.add(panel3, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        buttonOK = new JButton();
        buttonOK.setText("OK");
        panel3.add(buttonOK, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        final Spacer spacer1 = new Spacer();
        panel3.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_VERTICAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
        final JPanel panel4 = new JPanel();
        panel4.setLayout(new GridLayoutManager(2, 2, new Insets(0, 0, 0, 0), -1, -1));
        panel1.add(panel4, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        panel4.setBorder(BorderFactory.createTitledBorder(null, "包名称配置", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        final JLabel label1 = new JLabel();
        label1.setText("输入包名");
        panel4.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        final Spacer spacer2 = new Spacer();
        panel4.add(spacer2, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
        newPackageName = new JTextField();
        panel4.add(newPackageName, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return contentPane;
    }

}
